﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using intelliEssay.Core;
using intelliEssay.Core.DocumentStructure;
using intelliEssay.Interop;
using intelliEssay.Interop.ParagraphStyle;
using System.Text.RegularExpressions;
namespace intelliEssay.Checkers.BodyChecker
{
    public class intelliEssayBodyChecker : IEssayChecker
    {
        public void Run(intelliEssay.Core.Task task)
        {
            CheckBody(task);
            // throw new NotImplementedException();
        }

        public void Cancel(intelliEssay.Core.Task task)
        {
            // throw new NotImplementedException();
        }

        public string GetDescription(string cultureInfo)
        {
            return "Check the body of the document";
            // throw new NotImplementedException();

        }

        public string GetName(string cultureInfo)
        {
            return "body Checkers";
            // throw new NotImplementedException();
        }



        private void CheckBody(intelliEssay.Core.Task task)
        {
            //检查行距
            CheckLineSpacing(task);
            //检查字体和字体大小
            CheckBodyChineseAndEnglishFonts(task);

        }



        ///<summary>
        ///check the line spacing,the line spacing must be 1.5
        ///</summary>
        private void CheckLineSpacing(intelliEssay.Core.Task task)
        {
            //ParagraphInfoEx paragraphInfoEx = new ParagraphInfoEx(
            //RunInfoEx runInfo = new RunInfoEx();
            Paragraph standard = intelliEssay.Core.DocumentStructure.StandardFormats.GetStandardFormatByDocumentPart(intelliEssay.Core.DocumentStructure.DocumentParts.MainDocumentBody, 0, task);
            ParagraphInfoEx standardParagraphInfoEx = new ParagraphInfoEx(task.TaskObjectRoot, standard, task.taskSetting.hostApp);
            SpacingBetweenLines standardsptl = standardParagraphInfoEx["SpacingBetweenLines", true];

            /*
Indentation ind=            intelliEssay.Interop.ParagraphStyle.ParagraphPropertiesHelper.QParagraphPropertiesMultiValueProperty<Indentation>(new Paragraph(), task.TaskObjectRoot, task.taskSetting.hostA
            */
            for (int i = 0; i < task.documentStructure.MainDocumentBody.Count; ++i)
            {
                if (task.documentStructure.MainDocumentBody[i].InnerText.Trim() != "")
                {
                    if (Regex.IsMatch(task.documentStructure.MainDocumentBody[i].InnerText,"^[a-zA-Z]"))
                    {
                        continue;
                    }
                    if (task.documentStructure.MainDocumentBody[i].InnerText.Contains("纵观现在智能手机系统群雄纷争，2008年Google推出了一款名为Android的开源智能手机操作系统"))
                    {
                    }
                    ParagraphInfoEx paragraphinfoex = new ParagraphInfoEx(task.TaskObjectRoot, task.documentStructure.MainDocumentBody[i], task.taskSetting.hostApp);
                    SpacingBetweenLines spbtl = paragraphinfoex["SpacingBetweenLines", true];

                    /*比较行间距*/
                    if (!IsEqual(standardsptl, spbtl))
                    {
                        //错误
                        Console.WriteLine("wrong");
                        task.AddEssayExceptionToEssayExceptionCollection(new EssayException(ExceptionType.Formatting, "该段行距错误", task.documentStructure.MainDocumentBody[i], task, true));
                    }
                }

            }

            /*
          ParagraphInfoEx paragraphinfoex=new ParagraphInfoEx(task.TaskObjectRoot,task.documentStructure.MainDocumentBody[0],task.taskSetting.hostApp);
      SpacingBetweenLines spbtl=   paragraphinfoex["SpacingBetweenLines",true];
       */

            //standard.ParagraphProperties.SpacingBetweenLine

        }
        private bool IsEqual(SpacingBetweenLines A, SpacingBetweenLines B)
        {
            //本段和前段行距
            //if (A.BeforeAutoSpacing.Value != B.BeforeAutoSpacing.Value)
            // return false;
            if (A.AfterLines.Value != B.AfterLines.Value)
                return false;
            else if (A.After.Value != B.After.Value)
                return false;
            //本段和后段行距
            //if (A.AfterAutoSpacing.Value != B.AfterAutoSpacing.Value)
            //   return false;
            else if (A.AfterLines.Value != B.AfterLines.Value)
                return false;
            else if (A.After.Value != B.After.Value)
                return false;
            //本段内行距
            if (A.Line.Value != B.Line.Value)
                return false;
            return true;
        }
        /*****************************************************/
        /// <summary>
        /// check the body content font
        /// </summary>
        /// <param name="task"></param>
        private void CheckBodyChineseAndEnglishFonts(intelliEssay.Core.Task task)
        {
            Paragraph standardCN = intelliEssay.Core.DocumentStructure.StandardFormats.GetStandardFormatByDocumentPart(intelliEssay.Core.DocumentStructure.DocumentParts.MainDocumentBody, 0, task);
            Paragraph standardEN = StandardFormats.GetStandardFormatByDocumentPart(DocumentParts.MainDocumentBodyInEnglish, 0, task);
            // ParagraphInfoEx standardParagraphCNInfoEx = new ParagraphInfoEx(task.TaskObjectRoot, standardCN, task.taskSetting.hostApp);

            //ParagraphInfoEx standardParagraphENInfoEx=new ParagraphInfoEx(task.TaskObjectRoot,standardCN,task.taskSetting.hostApp);
            Run standardCNRun = standardCN.Elements<Run>().ToArray()[0];
            Run standardENRun = standardEN.Elements<Run>().ToArray()[0];
            RunInfoEx standardCNRunInfoEx = new RunInfoEx(task.TaskObjectRoot, standardCNRun, task.taskSetting.hostApp);
            RunInfoEx standardENRunInfoEx = new RunInfoEx(task.TaskObjectRoot, standardENRun, task.taskSetting.hostApp);
            string standardCNFont = standardCNRunInfoEx["runfonts"];
            string standardCNFontSize = standardCNRunInfoEx["fontsize"];

            string standardENFont = standardENRunInfoEx["runfonts"];
            string standardENFontSize = standardCNRunInfoEx["fontsize"];
            //  Console.WriteLine(standardENFont);
            Console.WriteLine(standardENFontSize);
            Console.WriteLine(standardCNFontSize);
            //FontSize standardCNFontSize=standardParagraphCNInfoEx["FontSize",true];

            //FontSize standardENFontSize=standardParagraphENInfoEx["FontSize",true];
            //Font standardCNFont=standardParagraphCNInfoEx["Font",true];
            //Font standardENFont=standardParagraphENInfoEx["Font",true];

            for (int i = 0; i < task.documentStructure.MainDocumentBody.Count; ++i)
            {
                // ParagraphInfoEx paragraphinfoex = new ParagraphInfoEx(task.TaskObjectRoot, task.documentStructure.MainDocumentBody[i], task.taskSetting.hostApp);
                var runs = task.documentStructure.MainDocumentBody[i].Elements<Run>().ToArray();
                for (int j = 0; j < runs.Count(); ++j)
                {
                    if (runs[j].InnerText.Trim() != "")
                    {
                        RunInfoEx taskRunInfoEx = new RunInfoEx(task.TaskObjectRoot, runs[j], task.taskSetting.hostApp);
                        string taskFont = taskRunInfoEx["runfonts"];
                        string taskFontSize = taskRunInfoEx["fontsize"];
                        //Console.WriteLine(taskFont);
                        //Console.WriteLine(taskFontSize);

                        string str = runs[j].InnerText;
                        int temp = IsSingleLanguage(runs[j].InnerText);
                        if (0 == temp)
                        {
                            //中文字体大小检查
                            if (standardCNFontSize != taskFontSize)
                            {
                                Console.WriteLine(taskFontSize);
                                task.AddEssayExceptionToEssayExceptionCollection(new EssayException(ExceptionType.Formatting, "字体大小错误" + taskFontSize, runs[j], task, true));
                            }
                            //中文字体检查
                            if (standardCNFont != taskFont)
                            {
                                Console.WriteLine(taskFont);
                                task.AddEssayExceptionToEssayExceptionCollection(new EssayException(ExceptionType.Formatting, "字体错误" + taskFont, runs[j], task, true));
                            }
                        }
                        else
                        {

                            //英文字体大小检查
                            if (standardENFontSize != taskFontSize)
                            {
                                Console.WriteLine(taskFontSize);
                                task.AddEssayExceptionToEssayExceptionCollection(new EssayException(ExceptionType.Formatting, "字体大小错误" + taskFontSize, runs[j], task, true));
                            }
                            //英文字体检查
                            if (standardENFont != taskFont)
                            {
                                Console.WriteLine(taskFont);
                                task.AddEssayExceptionToEssayExceptionCollection(new EssayException(ExceptionType.Formatting, "字体错误" + taskFont, runs[j], task, true));
                            }
                        }



                    }
                }

            }
        }
        private bool IsEnglish(string str)
        {
            for (int i = 0; i < str.Length; ++i)
            {
                if (!Char.IsLetter(str[i]))
                    return false;
            }
            return true;
        }
        /// <summary>
        /// 返回0 为中文 1为英文 -1为中英文皆有
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private int IsSingleLanguage(string str)
        {

            //  int flag = 0; //标记 0为中文 1为英文
            /*
            byte[] byte_len = Encoding.Default.GetBytes(str.Substring(0, 1));
            if (byte_len.Length==1)
                flag = 1;//为英文
            for (int i = 1; i < str.Length; ++i)
            {
                byte_len = Encoding.Default.GetBytes(str.Substring(i, 1));
                if (byte_len.Length == 1&&flag!=1||(byte_len.Length==2&&flag!=0))
                {
                    return -1;
                }
                       

            }
            return flag;*/
            byte[] byte_len = Encoding.Default.GetBytes(str.Substring(0, 1));
            if (byte_len.Length > 1)
                return 0;
            else
                return 1;
        }
        /***************************************************************/
        /// <summary>
        /// 检查正文段落对齐，每段首行空两格（中文开头），不空（英文）
        /// </summary>
        /// <param name="task"></param>
        public void CheckBodyParagraphAlignment(intelliEssay.Core.Task task)
        {



        }

    }


}
